package com.itjin.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itjin.config.JwtConfig;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Base64; // 新增：导入Base64工具类
import java.util.Date;

@Component
public class JwtUtil {
    private static JwtConfig jwtConfig;

    @Autowired
    public void setJwtConfig(JwtConfig config) {
        jwtConfig = config;
    }

    private static SecretKey getSigningKey() {
        // 核心修复：对jwtConfig.getBase64Secret()做Base64解码，得到32字节密钥
        String base64Secret = jwtConfig.getBase64Secret();
        // 1. Base64解码（关键步骤，之前缺失）
        byte[] decodedSecret = Base64.getDecoder().decode(base64Secret);
        // 2. 生成合规密钥（保留原有逻辑，仅改输入的字节数组）
        return Keys.hmacShaKeyFor(decodedSecret);
    }
    public static String generateToken(String userAccount, Integer userRole) {
        return Jwts.builder()
                .subject(userAccount)
                .claim("role", userRole)
                .expiration(new Date(System.currentTimeMillis() + jwtConfig.getExpiration()))
                .signWith(getSigningKey())
                .compact();
    }

    public static Boolean validateToken(String token, String username) {
        String usernameFromToken = extractUsername(token);
        return (usernameFromToken.equals(username) && !isTokenExpired(token));
    }

    public static String extractUsername(String token) {
        return extractClaim(token).getSubject();
    }

    public static Integer extractUserRole(String token) {
        Claims claims = extractClaim(token);
        return claims.get("role", Integer.class);
    }

    public static Boolean isTokenExpired(String token) {
        try {
            Date expiration = extractExpiration(token);
            return expiration.before(new Date());
        } catch (JwtException e) {
            throw new IllegalArgumentException("Invalid token", e);
        }
    }

    public static Date extractExpiration(String token) {
        try {
            return Jwts.parser()
                    .verifyWith(getSigningKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload()
                    .getExpiration();
        } catch (JwtException e) {
            throw new IllegalArgumentException("Invalid token", e);
        }
    }

    public static Claims extractClaim(String token) throws ExpiredJwtException, UnsupportedJwtException,
            MalformedJwtException, SecurityException, IllegalArgumentException {
        return Jwts.parser()
                .verifyWith(getSigningKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }
}